//
//  JZFrendeChatHTableViewCell.m
//  极致荟
//
//  Created by hetao on 14-5-15.
//  Copyright (c) 2014年 mac. All rights reserved.
//

#import "JZFrendeChatHTableViewCell.h"
#import "Expression.h"
#import "MMTextAttachment.h"
#import "ESImageViewController.h"
#import "JZHPersonaldetailsViewController.h"
@implementation JZFrendeChatHTableViewCell
Note * notedata;
NSMutableAttributedString *string;
- (void)awakeFromNib
{
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(taoges:)];
    [self addGestureRecognizer:tap];
    self.playimage.animationImages=[[NSArray alloc]initWithObjects:[UIImage imageNamed:@"yu1"], [UIImage imageNamed:@"yu2"],[UIImage imageNamed:@"yu3"],nil];
    self.playimage.animationDuration=1.5;
    self.playimage.animationRepeatCount=0;
    self.rcorder=[Rrcorder defule];
    
    [self.pothimage.layer setCornerRadius:6.0];
    [self.pothimage.layer setMasksToBounds:YES];
    [self.pothimage.layer setBorderWidth:1];
    [self.pothimage setUserInteractionEnabled:YES];
    [self.pothimage.layer setBorderColor:[[UIColor whiteColor] CGColor]];
    [self.pothimage addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showImage:)]];
    
    [self.mpview.layer setCornerRadius:6.0];
    [self.mpview.layer setMasksToBounds:YES];
    [self.mpview.layer setBorderWidth:1];
    [self.mpview.layer setBorderColor:[[UIColor grayColor] CGColor]];
    
    [self.mpimage.layer setCornerRadius:6.0];
    [self.mpimage.layer setMasksToBounds:YES];
    [self.mpimage setUserInteractionEnabled:YES];
    [self.mpimage addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pusptosh:)]];
  
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopnot:) name:STOPPLAY object:nil];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)pusptosh:(UITapGestureRecognizer *)tap
{
    NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:[_notedata.content dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
    OtherUsers *ouser=[[OtherUsers alloc] init];
    ouser.userId=[[dic objectForKey:@"id"] intValue];
    ouser.userHeadImage=[dic objectForKey:@"headimage"];
    ouser.name=[dic objectForKey:@"name"];
    [self.viewcontroller.navigationController pushViewController:[JZHPersonaldetailsViewController shareName:ouser]  animated:YES];
}

- (void)taoges:(UITapGestureRecognizer *)tap
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    [UIView animateWithDuration:0.35 animations:^{
        [[Expression shareExpression:nil viewconncrerll:nil] hidden];
         [self.viewcontroller.view setCenter:CGPointMake(160, self.viewcontroller.view.frame.size.height/2)];
        [self.viewcontroller.toolView setFrame:CGRectMake(0, HEIGHT+20, self.viewcontroller.toolView.frame.size.width, self.viewcontroller.toolView.frame.size.height)];
        self.viewcontroller.toolbut.selected=NO;
        self.viewcontroller.expression.selected=NO;
    }];
    
}

- (void)showImage:(UITapGestureRecognizer *)tap
{
    ESImageViewController *ivc = [[ESImageViewController alloc] init];
    [ivc setTappedThumbnail:self.pothimage];
    [ivc setImage:self.pothimage.image];
    [self.viewcontroller presentViewController:ivc animated:YES completion:nil];
}
- (IBAction)playbuts:(UIButton *)sender
{
    if(sender.selected)
    {
        [self.rcorder stoprecorder];
        sender.selected=NO;
    }else
    {
        
        [self.rcorder stoprecorder];
        [self.playimage startAnimating];
        [self.rcorder recorderplayerData:_notedata.content];
        sender.selected=YES;
    }
}
- (CGFloat)addCellData:(Note *)note  user:(User *)ouser
{
    self.playview.hidden=YES;
    self.content.hidden=YES;
    self.pothview.hidden=YES;
    self.mpview.hidden=YES;
    _notedata=note;
    [ImageCache imageUrl:ouser.userHeadImage UiImageview: self.headimage];
    CGRect rect=self.contentview.frame;
    if(note.noteType==VOICE)//当显示内容为语音时
    {
        [self.contentview setFrame:CGRectMake(rect.origin.x, rect.origin.y, 145,33)];
        self.playview.hidden=NO;
        
        //self.vodeleng.text=[NSString stringWithFormat:@"%@''",note.vodeleng];
        return self.frame.size.height;
    }
    
    if(note.noteType==BC)
    {
        self.mpview.hidden=NO;
        [self.contentview setFrame:CGRectMake(rect.origin.x, rect.origin.y, 193,95)];
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:[note.content dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
        self.mpimage.tag=200+[[dic objectForKey:@"id"] intValue];
        [ImageCache imageUrl:[dic objectForKey:@"headimage"] UiImageview:self.mpimage];
        self.mpname.text=[dic objectForKey:@"name"];
        return 110;
    }
    if(note.noteType==IMAGE)
    {
       [self.contentview setFrame:CGRectMake(rect.origin.x, rect.origin.y, 105,147)];
        self.pothview.hidden=NO;
        [ImageCache imageUrl:self.notedata.content UiImageview:self.pothimage];
         CGFloat hige=self.contentview.frame.size.height+10;
         [self.contentView setFrame:CGRectMake(self.contentView.frame.origin.x, self.contentView.frame.origin.y, self.contentView.frame.size.width, hige)];
        return 160;
    }
    self.content.hidden=NO;
    [self faceDolo:note.content];
    
    
    if(self.content.frame.size.height+10<=33)
    {
    [self.contentview setFrame:CGRectMake(rect.origin.x, rect.origin.y, self.content.frame.size.width+20, 33)];
    }else
    {
    [self.contentview setFrame:CGRectMake(rect.origin.x, rect.origin.y, self.content.frame.size.width+20, self.content.frame.size.height+10)];
    }
    
 
    
    CGFloat hige=self.contentview.frame.origin.y+self.content.frame.size.height+40;
    [self.contentView setFrame:CGRectMake(self.contentView.frame.origin.x, self.contentView.frame.origin.y, self.contentView.frame.size.width, hige)];
    
    return hige;
}

///表情替换  实现的基本逻辑是，先根据字符表情串，找出它的位置，长度为1
- (void)faceDolo:(NSString *)content
{
    NSArray *farr=[content componentsSeparatedByString:@";"];//根据‘;’截取出对应的数组
  
    NSMutableArray *fmuarr=[[NSMutableArray alloc]init];//用于保存最终截取到的表情字符
    for(NSString *str in farr)
    {
        NSArray *arr=[str componentsSeparatedByString:@"/"];//从‘;’中得到的数组在根据‘/’截取
       // NSLog(@"%@",arr);
        for(NSString *str2 in arr)
        {
            if(str2.length==2 || str2.length==3)//从‘/’中的截取结果来判断是否是表情字符
            {
                NSString *esc=[str2 substringToIndex:1];
                if([esc isEqualToString:@"f"])
                {
                    NSString *zostr=[str2 substringFromIndex:1];
                    [fmuarr addObject:zostr];
                }
            }
        }
        
    }
    
    
    NSString *zzstr=content;//存不含字符表情的纯文本
    for(NSString *ths in fmuarr)
    {
        zzstr=[zzstr stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"/f%@;",ths] withString:@""];
    }
    
    string=nil;
    string=[[NSMutableAttributedString alloc]initWithString:zzstr attributes:nil];
    
    NSString *maxcon=content;//用于装载替换过后的文本
    
    for(int i=0;i<fmuarr.count;i++)//查找表情字符的位置，
    {
        NSString *indexstr=fmuarr[i];
      maxcon=[self stringIndex:maxcon tostring:indexstr];
    }
    
    self.content.attributedText = string;
    [self.content sizeToFit];
   
}


//根据给的文本内容查找出某个字符表情的位置
- (NSString *)stringIndex:(NSString *)str tostring:(NSString *)tostr
{
    NSString*tstr;//用于存放替换过的文本
    
    NSRange range;
    range = [str rangeOfString:[NSString stringWithFormat:@"/f%@;",tostr]];
    
    if (range.location != NSNotFound)
    {
        //如果在文本中找到该表情字符,则用一个字符替代，这样做的目的只是为后面的表情字符找到准确的位置，本身不用来显示成最终文本
        tstr = [str stringByReplacingCharactersInRange:range withString:@"*"];
        
        //开始生成表情图片并添加到文本
        MMTextAttachment *atac=[[MMTextAttachment alloc]initWithData:nil ofType:nil];
        UIImage * smileImage = [ UIImage imageNamed:[NSString stringWithFormat:@"%@f.gif",tostr]];
        atac.image=smileImage;
        NSAttributedString * textAttachmentString = [ NSAttributedString attributedStringWithAttachment:atac];
        
        [string insertAttributedString:textAttachmentString atIndex:range.location ] ;
    }
    return tstr;
}
#pragma mark------录音播放停止通知-----
- (void)stopnot:(NSNotification *)not
{
    self.playbut.selected=NO;
    [self.playimage stopAnimating];
}
@end
